package com.example.demo.controller.equipment;

import com.example.demo.domain.equipment.Budget;
import com.example.demo.service.equipment.BudgetService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping
@CrossOrigin
public class BudgetController {
    @Resource
    @Autowired
    private BudgetService budgetService;
    private List<Budget> budgetList;

    @PostMapping(value = "/add-budget")
    public Budget addBudget(@RequestBody Budget budget) {
        return budgetService.addbudget(budget);
    }

    @GetMapping(value = "/budget-list")
    public String getBudget(@RequestParam("planId") String planId){
        budgetList=budgetService.getBudget(planId);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("number",budgetList.size());
        jsonArray.add(jsonObject);
        List<Budget> budgets = budgetList;
        for (Budget temp:budgets){
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("ticketId",temp.getTicketId());
            jsonObject1.put("planId",temp.getPlanId());
            jsonObject1.put("budgetItem",temp.getBudgetItem());
            jsonObject1.put("budgetNum",temp.getBudgetNum());
            jsonObject1.put("remark",temp.getRemark());
            jsonArray.add(jsonObject1);
        }
        return jsonArray.toString();
    }

    @GetMapping(value = "/search-by-ticket-id")
    public Budget getbyid(@RequestParam("ticketId") Integer id){
        return budgetService.getBudgetbyTicketidMatched(id);
    }

    @PutMapping(value = "/edit-budget")
    public Budget editBudget(@RequestBody Budget budget){
        System.out.print(budget);
        return budgetService.editBudget(budget);
    }

    @DeleteMapping(value = "/delete-by-id")
    public void deleteBudget(@RequestParam("ticketId") Integer id){
        budgetService.deleteBudget(id);
    }
}
